package com.example.ffepeg.ffpeg;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.Scanner;

@Slf4j
public class Main {
    public static void main(String[] args) {
        // 给定的日期时间
      /*  String givenDateTimeStr = "2025-02-07 10:27:00";
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime givenDateTime = LocalDateTime.parse(givenDateTimeStr, formatter);
        LocalDateTime now = LocalDateTime.now();
        if (now.toLocalDate().isAfter(givenDateTime.toLocalDate())) {
            System.out.println("当前日期大于2025-02-07");
        } else {
            LocalDateTime oneHourLater = givenDateTime.plusHours(1);
            // 比较当前时间是否大于给定时间加一小时
            if (now.isAfter(oneHourLater)) {
                System.err.println("当前时间大于" + oneHourLater.format(formatter));
            }
        }*/

        String txUrl = "https://pushimg.liecaizhijia.com/video/gen/2024-09-24/89a32ab1-3657-4e56-a83f-bda21593f817.mp4";
        String bdPath = "D:\\javaXM\\FFEpeg\\src\\main\\resources\\out\\outputWithMusic.mp4";
       // boolean downVideo = downVideo(txUrl, bdPath);
        //System.out.println(downVideo);


        Integer i = videoTime(txUrl, true);
        System.out.println(i);

    }

    public static Integer videoTime(String videoPath,boolean stem){
        try {
            Process process;
            if(stem) {
                process = Runtime.getRuntime().exec(
                        "ffprobe -i " + videoPath +
                                " -show_entries format=duration -v quiet -of csv=\"p=0\" -threads 2"
                );
            }else {
                process = Runtime.getRuntime().exec(new String[]{
                        "/www/server/ffmpeg/ffmpeg-6.1/ffprobe",
                        "-i", videoPath,
                        "-show_entries", "format=duration",
                        "-v", "quiet",
                        "-of", "csv=p=0",
                        "-threads", "2"
                });
            }
            // 读取输出
            int time = 0;
            try (Scanner scanner = new Scanner(process.getInputStream()).useDelimiter("\\A")) {
                if (scanner.hasNext()) {
                    String durationStr = scanner.next().trim();
                    double duration = Double.parseDouble(durationStr);
                    time = (int) duration;
                }
            }catch (Exception e){
                throw new RuntimeException("获取视频时长失败");
            }
            return time;
        }catch (Exception e){
            throw new RuntimeException(e.getMessage());
        }
    }


    public static void deleteFilesFromList(List<String> filePathStrings) {
        for (String filePathString : filePathStrings) {
            Path path = Paths.get(filePathString);
            try {
                if (Files.exists(path) && Files.isRegularFile(path)) {
                    Files.delete(path);
                    log.info("文件删除成功: " + path);
                } else {
                    log.error("文件不存在或不是常规文件: " + path);
                }
            } catch (IOException e) {
                log.error("文件删除失败: " + path);
            }
        }
    }



    /**
     * 下载视频
     * @param videoUrl 视频网络地址
     * @param downloadPath  视频保存地址
     */
    public static boolean downVideo(String videoUrl, String downloadPath) {
        HttpURLConnection connection = null;
        InputStream inputStream = null;
        RandomAccessFile randomAccessFile = null;
        boolean re;
        try {
            URL url = new URL(videoUrl);
            connection = (HttpURLConnection) url.openConnection();
            connection.setRequestProperty("Range", "bytes=0-");
            connection.connect();
            if (connection.getResponseCode() / 100 != 2) {
                System.out.println("连接失败...");
                return false;
            }
            inputStream = connection.getInputStream();
            int downloaded = 0;
            int fileSize = connection.getContentLength();
            randomAccessFile = new RandomAccessFile(downloadPath, "rw");
            while (downloaded < fileSize) {
                byte[] buffer = null;
                if (fileSize - downloaded >= 1000000) {
                    buffer = new byte[1000000];
                } else {
                    buffer = new byte[fileSize - downloaded];
                }
                int read = -1;
                int currentDownload = 0;
                long startTime = System.currentTimeMillis();
                while (currentDownload < buffer.length) {
                    read = inputStream.read();
                    buffer[currentDownload++] = (byte) read;
                }
                long endTime = System.currentTimeMillis();
                double speed = 0.0;
                if (endTime - startTime > 0) {
                    speed = currentDownload / 1024.0 / ((double) (endTime - startTime) / 1000);
                }
                randomAccessFile.write(buffer);
                downloaded += currentDownload;
                randomAccessFile.seek(downloaded);
                System.out.printf(downloadPath+"下载了进度:%.2f%%,下载速度：%.1fkb/s(%.1fM/s)%n", downloaded * 1.0 / fileSize * 10000 / 100,
                        speed, speed / 1000);
            }
            re = true;
            return re;
        } catch (MalformedURLException e) {
            e.printStackTrace();
            re = false;
            return re;
        } catch (IOException e) {
            e.printStackTrace();
            re = false;
            return re;
        } finally {
            try {
                connection.disconnect();
                inputStream.close();
                randomAccessFile.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }




}
